<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Redis的使用及高可用部署, Python,HTML,CSS,JavaScript,Web安全等">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Redis的使用及高可用部署 | 孤狼</title>
    <link rel="icon" type="image/png" href="/a.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
	<script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>

<meta name="generator" content="Hexo 5.4.0"><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
			<div class="brand-logo">
				<a href="/" class="waves-effect waves-light">
					<div>
						
						<img src="/loading.gif" data-original="/medias/logo.png" class="logo-img" alt="LOGO">
						
						<span class="logo-span">孤狼</span>
					</div>
				</a>
			</div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">

      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/categories/linux">
          
          <span>linux</span>
        </a>
      </li>
      
      <li>
        <a href="/categories/python">
          
          <span>python</span>
        </a>
      </li>
      
      <li>
        <a href="/categories/%E5%8D%9A%E5%AE%A2">
          
          <span>博客</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/loading.gif" data-original="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">孤狼</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-bookmark"></i>
			
			分类
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/categories/linux " style="margin-left:75px">
				  
		          <span>linux</span>
                  </a>
                </li>
              
                <li>

                  <a href="/categories/python " style="margin-left:75px">
				  
		          <span>python</span>
                  </a>
                </li>
              
                <li>

                  <a href="/categories/%E5%8D%9A%E5%AE%A2 " style="margin-left:75px">
				  
		          <span>博客</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/11.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Redis的使用及高可用部署</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/linux/">
                                <span class="chip bg-color">linux</span>
                            </a>
                        
                            <a href="/tags/redis/">
                                <span class="chip bg-color">redis</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/linux/" class="post-category">
                                linux
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-03-31
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    3.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    16 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="Redis的使用"><a href="#Redis的使用" class="headerlink" title="Redis的使用"></a>Redis的使用</h1><h2 id="Redis的安装启动及配置文件"><a href="#Redis的安装启动及配置文件" class="headerlink" title="Redis的安装启动及配置文件"></a>Redis的安装启动及配置文件</h2><h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><p>CentOS:</p>
<pre class=" language-shell"><code class="language-shell">yum install redis

# 配置文件默认在
vim /etc/redis.conf
</code></pre>
<p>Ubuntu</p>
<pre class=" language-shell"><code class="language-shell">apt-get install redis

# 配置文件默认在
sudo vim /etc/redis/redis.conf
</code></pre>
<h3 id="配置文件修改如下"><a href="#配置文件修改如下" class="headerlink" title="配置文件修改如下"></a>配置文件修改如下</h3><pre class=" language-shell"><code class="language-shell">sudo vim /etc/redis/redis.conf
# 进入配置文件后，为了方便修改  使用vim语法：/要搜索的内容  进行搜索。
# 比如在扩展模式在直接输入：/bind   然后回车，表示搜索bind,此时按n为下一个 

# 这里是绑定redis的启动地址，如果你支持远程连接，把bind改为0.0.0.0
bind 0.0.0.0

# 设置端口
port 6500

# 设置redis的密码为haohaio
requirepass haohaio

# 默认打开了安全模式
protected-mode yes

# 打开一个redis后台运行的参数
daemonize yes
</code></pre>
<h3 id="启动Redis"><a href="#启动Redis" class="headerlink" title="启动Redis"></a>启动Redis</h3><pre class=" language-shell"><code class="language-shell">systemctl start redis

# 如果你按我的设置进行操作，将会提示无法连接，为什么呢？
# 因为这个命令默认连接6379端口，我们改了redis端口，因此无法连接了。

# 使用如下命令，指定配置文件启动
test@bogon:~$ sudo redis-server /etc/redis/redis.conf 

# 检查redis的进程
test@bogon:~$ ps -ef |grep redis
root        2225       1  0 15:59 ?        00:00:00 redis-server 0.0.0.0:6500
test        2231    1495  0 15:59 pts/1    00:00:00 grep --color=auto redis
</code></pre>
<h3 id="连接Redis服务端，指定端口及密码连接redis"><a href="#连接Redis服务端，指定端口及密码连接redis" class="headerlink" title="连接Redis服务端，指定端口及密码连接redis"></a>连接Redis服务端，指定端口及密码连接redis</h3><pre class=" language-shell"><code class="language-shell">test@bogon:~$ redis-cli -p 6500 
127.0.0.1:6500> ping
(error) NOAUTH Authentication required.
127.0.0.1:6500> auth haohaio
OK
127.0.0.1:6500> ping
PONG
</code></pre>
<h2 id="Redis数据持久化操作rdb与aof"><a href="#Redis数据持久化操作rdb与aof" class="headerlink" title="Redis数据持久化操作rdb与aof"></a>Redis数据持久化操作rdb与aof</h2><pre class=" language-shell"><code class="language-shell">向redis中写入一些数据，重启进程，查看数据是否存在

# 1.环境准备，准备一个redis.conf配置文件，不开启数据持久化
test@bogon:~$ cat no_rdb_redis.conf
bind 0.0.0.0
daemonize yes

# 2.指定该文件启动
test@bogon:~$ redis-server no_rdb_redis.conf

# 3.登录数据库，写入数据，然后退出数据库杀死进程，查看数据是否存在
</code></pre>
<p>以上操作是为了演示未配置持久化数据会丢失</p>
<h3 id="rdb机制的数据持久化"><a href="#rdb机制的数据持久化" class="headerlink" title="rdb机制的数据持久化"></a>rdb机制的数据持久化</h3><pre class=" language-shell"><code class="language-shell"># RDB持久化产生的RDB文件是一个经过压缩的二进制文件，我们看不懂的，这个文件被保存在硬盘中，redis可以通过这个文件还原数据库当时的状态。

# 1. vim /opt/redis/redis.conf,写入如下内容

daemonize yes  # 后台运行
port 6379      # 端口
logfile /data/6379/redis.log  # 指定redis的运行日志，存放位置
dir /data/6379              # 定义持久化文件存储位置
dbfilename  dbmp.rdb        # 指定数据rdb持久化文件的名字
bind 10.0.0.10  127.0.0.1    # redis绑定地址
requirepass redhat            # redis登录密码
# 900秒内有1个修改的命令操作，如set .mset del
save 900 1                    # rdb机制 每900秒 有1个修改操作，触发
save 300 10                    # 每300秒        10个修改操作，触发
save 60  10000                # 每60秒内        10000修改操作，触发

# 2.创建redis的数据文件夹
mkdir -r /data/6379

# 3.指定配置了rdb的redis配置文件，启动
sudo redis-server /opt/redis/redis.conf

# 4.如果没有触发redis的持久化时间机制，数据文件是不会生成的，数据重启进行也会丢

# 5.可以通过编写脚本，让redis手动执行save命令，触发持久化，在redis命令行中直接输入save即可触发持久化

# 6.存在了rdb持久化的文件之后，重启redis进程，数据也不会丢了，redis在重启之后，会读取dbmp.rdb文件中的数据

# 7.rdb的弊端在于什么，如果没有触发持久化机制，就发生了机器宕机，数据就会丢失了，因此redis有一个更好的aof机制
</code></pre>
<h3 id="aof机制的数据持久化"><a href="#aof机制的数据持久化" class="headerlink" title="aof机制的数据持久化"></a>aof机制的数据持久化</h3><pre class=" language-shell"><code class="language-shell"># AOF（append-only log file）
# 记录服务器执行的所有变更操作命令（例如set del等），并在服务器启动时，通过重新执行这些命令来还原数据集
# AOF 文件中的命令全部以redis协议的格式保存，新命令追加到文件末尾。
# 优点：最大程序保证数据不丢
# 缺点：日志记录非常大
</code></pre>
<pre class=" language-shell"><code class="language-shell">AOF持久化配置，两条参数

appendonly  yes      # 开启aof功能

appendfsync always   # 总是修改类的操作
            everysec  # 每秒做一次持久化（正常都够用了）
            no        # 依赖于系统自带的缓存大小机制
</code></pre>
<pre class=" language-shell"><code class="language-shell"># 1.准备aof配置文件 redis.conf
# vim /data/redis.conf
daemonize yes
port 6379
logfile /data/6379aof/redis.log
dir /data/6379aof
dbfilename  dbmp.rdb
requirepass redhat
appendonly yes   
appendfsync everysec

# 2.创建aof的数据文件夹
mkdir -r /data/6379aof

# 3.启动redis服务
redis-server /etc/redis.conf

# 4.aof机制的数据库，在首次启动的时候，就会生成aof数据文件了

# 5.登录redis，写入数据，检查数据是否持久化。可以用tail -f监测日志变化

# 6.写入的操作，会被记录到aof文件中
</code></pre>
<h2 id="Redis主从复制故障切换"><a href="#Redis主从复制故障切换" class="headerlink" title="Redis主从复制故障切换"></a>Redis主从复制故障切换</h2><p>在一台机器上运行2个及以上的redis，是redis支持多实例的功能，基于端口号的不通，就能够运行多个相互独立的redis数据库</p>
<pre class=" language-shell"><code class="language-shell"># 什么是多实例？
# 就是机器上运行了多个redis相互独立的进程
# 互不干扰的独立数据库
# 叫做多个redis数据库的实例，基于配置文件区分即可
</code></pre>
<pre class=" language-shell"><code class="language-shell"># 1.上午的最后一步，演示的是当我们删除aof文件，或者rdb，aof文件异常损坏，丢失，数据不也没了吗？
</code></pre>
<p>操作笔记：</p>
<h3 id="一主一从-较简单，高可用性不高"><a href="#一主一从-较简单，高可用性不高" class="headerlink" title="一主一从(较简单，高可用性不高)"></a>一主一从(较简单，高可用性不高)</h3><p>如图是redis的多实例功能，且配置主从同步的图</p>
<img src="/loading.gif" data-original="/posts/26528/redis%E4%B8%BB%E4%BB%8E%E5%90%8C%E6%AD%A5.png" class="" title="{redis主从同步}">

<pre class=" language-shell"><code class="language-shell"># 1.准备好2个redis的配置文件，分别写入如下内容

# vim   /data/6380/redis-master.conf
port 6380
daemonize yes
pidfile /data/6380/redis.pid
loglevel notice    # 日志级别，普通的verbose，常用于生产环境
logfile "/data/6380/redis.log"
dbfilename dump.rdb
dir /data/6380
protected-mode no

# vim   /data/6381/redis-slave.conf
port 6381
daemonize yes
pidfile /data/6381/redis.pid
loglevel notice
logfile "/data/6381/redis.log"
dbfilename dump.rdb
dir /data/6381
protected-mode no
slaveof 127.0.0.1 6380 # 也可以直接在配置文件中定义好复制关系，启动后，立即就会建立复制

# 2.分别生成两个redis的数据文件夹
mkdir -p /data/&#123;6380,6381&#125;

# 3.分别启动2个redis数据库
redis-server /data/6380/redis-master.conf
redis-server /data/6381/redis-slave.conf

# 4.分别检查他们的进程，以及复制关系
`test@bogon:/data/6381$ redis-cli -p 6380 info replication
role:master
connected_slaves:0
master_replid:5c8f1698e3aec10fce8db9223b6719e1388ee6e2
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0
`test@bogon:/data/6381$ redis-cli -p 6381 info replication
role:master
connected_slaves:0
master_replid:b5a0572e1b4e5bb2b59edad63265129b02219a20
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

# 通过一条命令，配置他们的复制关系，注意，这个命令只是临时配置redis的复制关系，想要永久修改，还得修改配置文件
# redis-cli -p 要设置的奴隶端口号 slaveof 主的地址 主端口号
`test@bogon:/data/6381$ redis-cli -p 6381 slaveof 127.0.0.1 6380
OK
`test@bogon:/data/6381$ redis-cli -p 6381 info replication
# Replication
role:slave  # 当前redis角色，slave奴隶
master_host:127.0.0.1   # 连接主机
master_port:6380        # 连接端口
master_link_status:up   # 连接状态

# 5.此时6380已然是主库，6381已然是从库
此时可以向6380写入，会同步到6381中，且6381是一个只读库，无法写入数据
</code></pre>
<img src="/loading.gif" data-original="/posts/26528/redis%E4%B8%80%E4%B8%BB%E5%A4%9A%E4%BB%8E.png" class="" title="{redis一主多从}">

<h3 id="一主多从的形式，一级主从复制故障切换"><a href="#一主多从的形式，一级主从复制故障切换" class="headerlink" title="一主多从的形式，一级主从复制故障切换"></a>一主多从的形式，一级主从复制故障切换</h3><pre class=" language-shell"><code class="language-shell"># 1.在创建一个配置文件，port是6399，且加入到一主一从的复制关系中去
# vim /data/6399/redis-slave2.conf
port 6399
daemonize yes
pidfile /data/6399/redis.pid
loglevel notice
logfile "/data/6399/redis.log"
dbfilename dump.rdb
dir /data/6399
protected-mode no
slaveof 127.0.0.1 6380

# 2.启动6399的数据库，查看他的身份复制关系
`test@bogon:/data/6381$ redis-cli -p 6399 info replication
</code></pre>
<img src="/loading.gif" data-original="/posts/26528/redis%E6%95%85%E9%9A%9C%E6%A8%A1%E6%8B%9F.png" class="" title="{redis故障模拟}">

<pre class=" language-shell"><code class="language-shell"># 1.环境准备，准备3个redis的数据库实例，分别是 6379,6389,6399，配置好一主两从的关系
`test@bogon:/data/6399$ ps -ef | grep redis
root        5651       1  0 11:05 ?        00:00:10 redis-server *:6380
root        5661       1  0 11:05 ?        00:00:09 redis-server *:6381
root        5821       1  0 11:30 ?        00:00:07 redis-server *:6399

分别查看复制关系
`test@bogon:/data/6399$ redis-cli -p 6380 info replication
# Replication
role:master
connected_slaves:2
slave0:ip=127.0.0.1,port=6381,state=online,offset=1904,lag=0
slave1:ip=127.0.0.1,port=6399,state=online,offset=1904,lag=0

# 2.此时直接干掉主库即可
kill 6380的pid即可

# 3.此时留下2个从库，还没法写入数据

# 4.这时一位从库不乐意了，翻身农奴做主人
`test@bogon:/data/6399$ redis-cli -p 6381 slaveof no one`

# 5.此时6381已然是主库了，修改6399的复制信息
`test@bogon:/data/6399$ redis-cli -p 6399 slaveof 127.0.0.1 6381`

# 6.此时检查他们的复制关系

# 7.此时可以向6381写入数据，6399查看数据即可
</code></pre>
<p>你会发现，如此的手动切换复制关系其实是很难受的，如果在夜里凌晨，redis主库突然挂了，怎么办？</p>
<h2 id="Redis-Sentinel高可用哨兵"><a href="#Redis-Sentinel高可用哨兵" class="headerlink" title="Redis Sentinel高可用哨兵"></a>Redis Sentinel高可用哨兵</h2><h3 id="redis哨兵的工作原理"><a href="#redis哨兵的工作原理" class="headerlink" title="redis哨兵的工作原理"></a>redis哨兵的工作原理</h3><pre class=" language-shell"><code class="language-shell">配置好redis哨兵进程，一般都是使用3个哨兵(保安)
哨兵的作用是盯着redis主库，不断询问它是否存活，如果超过30s(设置的时间阈值)都没有回应，3个哨兵会判断主库宕机，谈话进行投票机制，因为3个哨兵要自动的去选择从库为新的主库，每个哨兵的意见可能不一样
因此引出投票机制，少数服从多数
当多个哨兵意见达成一致，选择某一个从库，自动的修改他们的配置文件，切换为新的主库。
此时如果宕机的主库恢复后，哨兵也会自动将其加入集群，且自动分配为新的从库
这一些都是自动化的
</code></pre>
<img src="/loading.gif" data-original="/posts/26528/redis%E5%93%A8%E5%85%B5%E6%9E%B6%E6%9E%84.png" class="" title="{redis哨兵架构}">

<h3 id="哨兵集群的配置"><a href="#哨兵集群的配置" class="headerlink" title="哨兵集群的配置"></a>哨兵集群的配置</h3><pre class=" language-shell"><code class="language-shell"># 1.准备3个redis主从复制的redis实例，1主2从，启动并确认数据库关系信息
上面已经有了，省略。。。

# 2.三个redis-sentinel配置文件写入如下,三个哨兵的配置仅仅是端口号不同

# vim redis-sentinel-26380.conf
# Sentinel节点的端口
port 26380  
dir /var/redis/data/
logfile "26380.log"
# 当前Sentinel节点监控 127.0.0.1:6380 这个主节点
# 2代表判断主节点失败至少需要2个Sentinel节点节点同意
# mymaster是主节点的别名
sentinel monitor mymaster 127.0.0.1 6380 2
# 每个Sentinel节点都要定期PING命令来判断Redis数据节点和其余Sentinel节点是否可达，如果超过30000毫秒30s且没有回复，则判定不可达
sentinel down-after-milliseconds mymaster 30000
# 当Sentinel节点集合对主节点故障判定达成一致时，Sentinel领导者节点会做故障转移操作，选出新的主节点，
# 原来的从节点会向新的主节点发起复制操作，限制每次向新的主节点发起复制操作的从节点个数为1
sentinel parallel-syncs mymaster 1
# 故障转移超时时间为180000毫秒
sentinel failover-timeout mymaster 18000
# 后台运行
daemonize yes

# 3.启动哨兵
redis-sentinel redis-sentinel-26380.conf
`# 如果提示命令不存在，检查一下输入redis- ，然后按两次tab补全查看是否有redis-sentinel`
`# 如果没有redis-sentinel，比如我使用的kali就没有，`
`# 下载方式：apt-get install redis-sentinel`

# 4.查看哨兵状态
`test@bogon:/data/sentinel$ redis-cli -p 26380 info sentinel`
# Sentinel
sentinel_masters:1
sentinel_tilt:0
sentinel_running_scripts:0
sentinel_scripts_queue_length:0
sentinel_simulate_failure_flags:0
master0:name=mymaster,status=ok,address=127.0.0.1:6380,slaves=2,sentinels=3
如果可以看到上面一行，则证明哨兵搭建成功

# 5.哨兵搭建好之后，模拟干掉主库，然后等待主从的一个自动化切换
- 检查6380的进程，杀死后，哨兵能够自动的进行投票选举，剩下来的一个slave为新的master，然后重新分配主从关系；
- 故障的修复，重启6380这个redis数据库，且检查它的一个复制关系
   6380数据库会重新加入到主从复制，且变为一个从库
- 如果你想恢复他们的主从关系，全部kill掉，重新启动，默认就会以配置文件分配主从关系了
</code></pre>
<h2 id="Redis集群redis-cluster"><a href="#Redis集群redis-cluster" class="headerlink" title="Redis集群redis-cluster"></a>Redis集群redis-cluster</h2><h3 id="集群"><a href="#集群" class="headerlink" title="集群"></a>集群</h3><img src="/loading.gif" data-original="/posts/26528/redis%E9%9B%86%E7%BE%A4.png" class="" title="{redis集群}">

<pre class=" language-shell"><code class="language-shell"># 1.准备好6匹马儿，也就是6个redis节点，也就是6个配置文件，redis集群节点最少是使用6个
这6个配置文件仅仅是端口号不同而已
redis-7000.conf
redis-7001.conf
redis-7002.conf
redis-7003.conf
redis-7004.conf
redis-7005.conf
`sed 's/7000/7002/g' redis-7000.conf > redis-7002.conf` # 命令替换，把7000替换为7002 

# vim redis-7000.conf
port 7000
daemonize yes
dir "/opt/redis/data"
logfile "7000.log"
dbfilename "dump-7000.rdb"
cluster-enabled yes  #开启集群模式
cluster-config-file nodes-7000.conf  #集群内部的配置文件
cluster-require-full-coverage no   #redis cluster需要16384个slot都正常的时候才能对外提供服务，换句话说，只要任何一个slot异常那么整个cluster不对外提供服务。 因此生产环境一般为no

# 2.分别启动了6个redis节点，且检查进程
redis-server redis-7000.conf
...

此时尝试写入数据，发现不能写入成功
我们仅仅是启动了6个redis节点，准备好了6匹马儿，马儿身上的框还没分配
</code></pre>
<p>此时准备好ruby的环境，用于一键创建redis集群，给马儿分配框，给redis节点分配slot槽位，用于写入数据</p>
<pre class=" language-shell"><code class="language-shell">### 注意！！！经过操作，建议先执行第5,6步，如果创建失败，再从1开始执行。一般5,6步可直接创建成功！

# 1.使用包管理工具进行安装
ruby====python   gem====pip  gem是ruby的包管理工具
# kali使用apt-get安装
apt-get insatll ruby
# Centos
yum install ruby

# 2.检查ruby和gem的环境
`test@bogon:/data/sentinel$ gem -v`
3.1.4
`test@bogon:/data/sentinel$ ruby -v`
ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-linux-gnu]

# 3.下载ruby操作redis的模块，用于创建集群
wget http://rubygems.org/downloads/redis-3.3.0.gem

# 4.用gem安装此模块
gem install -l redis-3.3.0.gem

# 5.搜索ruby创建redis集群的脚本
redis-trib.rb   如何知道它的绝对路径？
which是搜索PATH环境变量中的命令的绝对路径！
find才是搜索系统上的文件路径！！
find / -name redis-trib.rb

# --replicas 1  代表每个主节点，有一个从节点
# 6.1一键创建集群，中间输入yes即可，可能出现创建失败的问题，请看下图
`test@bogon:/data$ /usr/share/doc/redis-tools/examples/redis-trib.rb create --replicas 1 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005`

# 6.2 一键创建集群
`test@bogon:/data$ redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1`
</code></pre>
<img src="/loading.gif" data-original="/posts/26528/redis%E5%90%AF%E5%8A%A8%E9%9B%86%E7%BE%A41.png" class="" title="{redis启动集群1}">

<img src="/loading.gif" data-original="/posts/26528/redis%E5%90%AF%E5%8A%A8%E9%9B%86%E7%BE%A42.png" class="" title="{redis启动集群2}">

<h3 id="查看集群状态"><a href="#查看集群状态" class="headerlink" title="查看集群状态"></a>查看集群状态</h3><pre class=" language-shell"><code class="language-shell">redis-cli -p 7000 cluster info   # 集群状态

redis-cli -p 7000 cluster nodes  # 等同于查看nodes-7000.conf文件节点信息

redis-cli -p 7000 cluster nodes | grep master # 集群主节点状态

redis-cli -p 7000 cluster nodes | grep slave  # 集群从节点状态
</code></pre>
<p>集群状态</p>
<pre class=" language-shell"><code class="language-shell">`test@bogon:/data$ redis-cli -p 7000 cluster info`
cluster_state:ok
cluster_slots_assigned:16384
cluster_slots_ok:16384
cluster_slots_pfail:0
cluster_slots_fail:0
cluster_known_nodes:6
cluster_size:3
cluster_current_epoch:6
cluster_my_epoch:1
cluster_stats_messages_ping_sent:20
cluster_stats_messages_pong_sent:29
cluster_stats_messages_sent:49
cluster_stats_messages_ping_received:24
cluster_stats_messages_pong_received:20
cluster_stats_messages_meet_received:5
cluster_stats_messages_received:49
</code></pre>
<h3 id="测试写入集群数据"><a href="#测试写入集群数据" class="headerlink" title="测试写入集群数据"></a>测试写入集群数据</h3><p>登录集群必须使用redis-cli -c -p 7000,<strong>必须加上-c参数</strong></p>
<pre class=" language-shell"><code class="language-shell">test@bogon:/data$ redis-cli -c -p 7000
127.0.0.1:7000> set name2 "ccc"
OK
127.0.0.1:7000> set name3 111
OK
127.0.0.1:7000> keys *
1) "name3"
2) "name2"
127.0.0.1:7000> set name "aaa"
-> Redirected to slot [5798] located at 127.0.0.1:7001 # name已经自动分配到7001节点上
OK
127.0.0.1:7001> exit
</code></pre>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">aze</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://alinze.gitee.io/posts/26528.html">https://alinze.gitee.io/posts/26528.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">aze</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/linux/">
                                    <span class="chip bg-color">linux</span>
                                </a>
                            
                                <a href="/tags/redis/">
                                    <span class="chip bg-color">redis</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/loading.gif" data-original="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/loading.gif" data-original="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/posts/6255.html">
                    <div class="card-image">
                        
                        
                        <img src="/loading.gif" data-original="/medias/featureimages/7.jpg" class="responsive-img" alt="supervisor进程管理工具">
                        
                        <span class="card-title">supervisor进程管理工具</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-03-31
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/linux/" class="post-category">
                                    linux
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/linux/">
                        <span class="chip bg-color">linux</span>
                    </a>
                    
                    <a href="/tags/supervisor/">
                        <span class="chip bg-color">supervisor</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/36914.html">
                    <div class="card-image">
                        
                        
                        <img src="/loading.gif" data-original="/medias/featureimages/5.jpg" class="responsive-img" alt="Nginx的使用">
                        
                        <span class="card-title">Nginx的使用</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-03-31
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/linux/" class="post-category">
                                    linux
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/linux/">
                        <span class="chip bg-color">linux</span>
                    </a>
                    
                    <a href="/tags/nginx/">
                        <span class="chip bg-color">nginx</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="355992"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2022</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">aze</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
			 
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
             
             
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
             
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2021";
                    var startMonth = "3";
                    var startDate = "14";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">


    <a href="https://gitee.com/alinze" class="tooltipped" target="_blank" data-tooltip="访问我的Gitee" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1124302640@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1124302640" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1124302640" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="https://www.cnblogs.com/L521Z" class="tooltipped" target="_blank" data-tooltip="关注我的博客园: https://www.cnblogs.com/L521Z" data-position="top" data-delay="50">
        <i class="fab fa-juejin">博</i>
    </a>



</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    


	
	<!--浏览器搞笑标题  自定义添加  -->
	<script type="text/javascript">
		var OriginTitile=document.title,st;
		document.addEventListener("visibilitychange",function(){
			document.hidden?(document.title="ヽ(●-`Д´-)ノ你要玩捉迷藏嘛",clearTimeout(st)):(document.title="(Ő∀Ő3)ノ好哦！",st=setTimeout(function(){document.title=OriginTitile},3e3))
		})
	</script>
	<!--动态线条背景-->
	<script type="text/javascript"
		color="122 103 238" opacity='0.7' zIndex="-2" count="200" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js">
	</script>
	<!--樱花飘落效果 themes/matery/source/js/sakura.js-->
	<script type="text/javascript">
	//只在桌面版网页启用特效
	var windowWidth = $(window).width();
	if (windowWidth > 768) {
		document.write('<script type="text/javascript" src="/js/sakura.js"><\/script>');
	}
	</script>

<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=i;var e=n.imageLazyLoadSetting.isSPA,r=(n.imageLazyLoadSetting.preloadRatio,Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));function i(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight+240||document.documentElement.clientHeight+240)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}i(),n.addEventListener("scroll",function(){var t,e;t=i,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/haruto.model.json"},"display":{"position":"right","width":150,"height":300,"hOffset":20,"vOffset":-30},"mobile":{"show":true,"scale":0.5},"react":{"opacityDefault":0.7,"opacityOnHover":0.2},"log":false});</script></body>

</html>
